/* SharePoint Console Project
 * Http://SharePointConsole.codeplex.com
 * Copyright Jean-Alain Baeyens (2009)
 * Software under Microsoft Reciprocal License (Ms-RL)
 */

using System;
using System.Xml;
using System.Web.UI.WebControls.WebParts;

using Microsoft.SharePoint;
using Microsoft.SharePoint.WebPartPages;
using Sharepoint.Console.Commands;

namespace Sharepoint.Console.WebParts
{
    public class AddWebPart : RecursiveBaseCommande
    {
        public override string ShortHelp
        {
            get
            {
                return "Add a web part to a page.";
            }
        }

        public override string LongHelp
        {
            get
            {
                return "Add a web part to a page using ths xml web part definition file (dwp or webpart). You can also specify zone and index.";
            }
        }

        public override string Syntax
        {
            get
            {
                return "AddWebPArt 'PageUrl' 'pathToDwpFile' ['zoneId'] ['zoneIndex']";
            }
        }

        public override string Execute(string[] args)
        {
            if (args.Length != 3 && args.Length != 5) return string.Format("Invalide syntax. Use {0}", Syntax);

            string page = args[1];
            string dwpFilePath = args[2];

            SPLimitedWebPartManager wpm = null;
            string errorMessage;
            System.Web.UI.WebControls.WebParts.WebPart wp = null;

            XmlReader reader;

            try
            {
                wpm = this.SharepointConnection.Web.GetLimitedWebPartManager(page, PersonalizationScope.Shared);

                reader = XmlReader.Create(dwpFilePath);

                wp = wpm.ImportWebPart(reader, out errorMessage);

                reader.Close();
                
                if (wp != null)
                {

                    if (args.Length == 3)
                    {
                        //wpm.AddWebPart(wp, wp.Zone.ID, wp.ZoneIndex);
                        wpm.AddWebPart(wp, null, wp.ZoneIndex);
                    }

                    else
                    {
                        int index;

                        if (! int.TryParse(args[4], out index)) return "Invalid zone index";

                        wpm.AddWebPart(wp, args[3], index);
                    }
                    
                    return "Webpart added";
                }
                
                else
                {
                    return errorMessage;
                }
            }
            
            catch (Exception ex)
            {
                throw ex;
            }
        }
    }
}
